/**
 * Description: UDP广播接收端
 * File: udp_server.c |Time: 2021-04-12 13:48
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>

#define N 100

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage %s <broadcast ip> <port>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    char buff[N] = {0};

    // 绑定发送端信息
    struct sockaddr_in sendaddr;
    sendaddr.sin_family = AF_INET;
    sendaddr.sin_port = htons(atoi(argv[2]));
    sendaddr.sin_addr.s_addr = inet_addr(argv[1]);
    if (-1 == bind(sockfd, (struct sockaddr *)&sendaddr, 
                sizeof(struct sockaddr))) {
        perror("bind");
        return 0;
    }

    printf("broadcast %s is ready to receive.\n", argv[1]);
    while(1) {
        if (-1 == recvfrom(sockfd, buff, sizeof(buff), 0, NULL, NULL))
        {
            perror("recvfrom");
            return 0;
        }

        printf("broadcast received: %s\n", buff);
    }


    return 0;
}
